package com.leo.util;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.leo.dao.Dao;
import com.leo.entity.Score;
import com.leo.entity.Student;
import com.leo.entity.User;
import com.leo.vo.NetBugResult;


public class JiaowuNetBugImp implements JiaowuNetBug{
	
	public static void main(String[] args){
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		Dao dao = (Dao) ctx.getBean("dao");
//		JiaowuNetBugImp test = new JiaowuNetBugImp();
//		NetBugResult result = test.getScore("120202051012", "bin456389");
//		NetBugResult result2 = test.getInfo("120202051012", "bin456389");
//		JSONObject jsonObject = JSONObject.fromObject(result);
//		JSONObject jsonObject2 = JSONObject.fromObject(result2);
//		System.out.println(jsonObject.toString());
//		List<Score> scores = (List<Score>) result.getResult();
//		Student stu = (Student) result2.getResult();
//		stu.setStuID("123");
//		stu.getScores().addAll(scores);
//
//		for(Score  score: scores){
//			score.setStudent(stu);
//			dao.updateOrSave(score);
//		}
//		dao.updateOrSave(stu);

		String hql = "select u from User u "
				+ "inner join u.stuUids uid "
				+ "inner join uid.student s where u.username=? and s.stuID=?";
		User u = (User) dao.excuteQuery(hql, "user000", "123333");
	}
	private Map<String, String> cookies = null;
	private Connection connection = null;
    
    @Override
    public NetBugResult checkPassword(String stuID ,String password) {
    	return login(stuID, password, null);
    }
	
    public Connection getConnection(){
        if(connection == null) {
        	connection = Jsoup.connect("http://jiaowu.zhbit.com/default_ysdx.aspx") .timeout(10000);
        }
        return connection;
    }
    
    private Map<String, String> getCookies() throws IOException{
        Connection connection = getConnection();
        return cookies == null ? cookies = connection.execute().cookies() : cookies;
    }

    @Override
    public NetBugResult getInfo(String stuID ,String stuPassword) {
		try {
			
			Student student = null;
			
			NetBugResult result = login(stuID, stuPassword, "xsgrxx.aspx");
			
			Document doc = null;
			if("1".equals(result.getStatus())) {
				doc = (Document) result.getResult();
			} else {
				return result;
			}
			
			student = new Student();
			//学生班
			student.setClassName(doc.getElementById("lbl_xzb").text());
			//学院
			student.setCollege(doc.getElementById("lbl_xy").text());
			//入学日期
			student.setEntranceDate(doc.getElementById("lbl_rxrq").text());
			//当前所在级
			student.setGrade(doc.getElementById("lbl_dqszj").text());
			//学号
			student.setStuID(stuID);
			//密码
			student.setPassword(stuPassword);
			//姓名
			student.setName(doc.getElementById("xm").text());
			//电话
			student.setPhone(doc.getElementById("lbl_TELNUMBER").text());
			//专业名称
			student.setProfessional(doc.getElementById("lbl_zymc").text());
			//性别
			student.setSex(doc.getElementById("lbl_xb").text());
			
			return new NetBugResult("1", student);
			
		} catch (NullPointerException e) {
			return NetBugResult.networkError();
		}finally{
			logOut();
		}
	}

    @Override
	public NetBugResult getScore(String stuID ,String stuPassword) {
		try {
			
			List<Score> scores = new LinkedList<Score>();
			
			NetBugResult result = login(stuID, stuPassword, "xscj_gc.aspx");
			
			Document doc = null;
			if("1".equals(result.getStatus())) {
				doc = (Document) result.getResult();
			} else {
				return result;
			}
			
			String url = "http://jiaowu.zhbit.com/" + doc.getElementById("Form1").attr("action");
			String viewState = doc.getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
			
			connection.url(url).data(
				"Button1", "按学年查询",
				"__VIEWSTATE", viewState,
				"ddlXN", "",
				"ddlXQ", ""
					);
			
			doc = connection.cookies(cookies).post();
			
			Element table = doc.getElementById("Datagrid1").getElementsByTag("tbody").get(0);

			int count = table.children().size();
			for(int i = 1; i < count; i++) {
				Element line = table.child(i);
				Score score = new Score();
				//学年
				score.setSchoolYear(line.child(0).text());
				//学期
				score.setTerm(line.child(1).text());
				//课程ID
				score.setCourID(line.child(2).text());
				//课程名称
				score.setCourName(line.child(3).text());
				//课程类型
				score.setCourType(line.child(4).text());
				//学分
				score.setCredit(line.child(6).text());
				//绩点
				score.setGradePoint(line.child(7).text());
				//成绩
				score.setScore(line.child(8).text());
				//补考成绩
				score.setMakeupScore(line.child(10).text());
				//重修成绩
				score.setRepairScore(line.child(11).text());
				
				scores.add(score);
			}
			return new NetBugResult("1", scores);
			
		} catch (NullPointerException e) {
			return NetBugResult.networkError();
		} catch (IOException e) {
			//e.printStackTrace();
			return NetBugResult.networkError();
		}finally{
			logOut();
		}
	}
	
	/**
	 * @param page 登录成功后请求的页面，如学生个人信息是"xsgrxx.apsx"
	 * 
	 */
	private NetBugResult login(String stuID ,String password, String page) {
		//输入的账号密码非空
		if (stuID == null || password == null || stuID == "" || password == "") {
			return NetBugResult.stuIDOrPasswordError();
		}

		try {
			// 设置链接
            Connection connection = getConnection();
            // 得到cookies
            Map<String, String> cookies = getCookies();
            // 得到首页的doc
            Document doc = connection.cookies(cookies).get();
            // 获取input 中 name 为 __ViewState 的 value
            String viewState = doc.getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
			// 配置post参数
			connection.url("http://jiaowu.zhbit.com/default_ysdx.aspx")
				.data(
					"Button1", 			"  登录  ",
					"RadioButtonList1", "学生",
					"TextBox1", 		stuID,
					"TextBox2",			password,
					"__VIEWSTATE",		viewState
				);
	
			// post登录获取doc
			doc = connection.cookies(cookies).post();
			
			//判断是否登录成功
			if(doc.html().indexOf("xs_main.aspx?xh=") < 0) {
				return NetBugResult.stuIDOrPasswordError();
			}
			
			connection.url("http://jiaowu.zhbit.com/xs_main.aspx?xh=" + stuID)
					.cookies(getCookies()).get();
			doc = connection.url("http://jiaowu.zhbit.com/xs_main.aspx?xh=" + stuID)
					.cookies(getCookies()).get();
			
			if(page == null || page == "") {
				return new NetBugResult("1", "login success");
			}
			
			// 获取的url连接
			Elements links = doc.getElementsByAttributeValueContaining("href", page);

			if (links.isEmpty()) {
				return NetBugResult.networkError();
            }
			
			String url = "http://jiaowu.zhbit.com/" + links.get(0).attr("href");
			
			// 得到页面的doc
			doc = connection.url(url + "&type=1").cookies(cookies).get();
			
			if(doc.html().indexOf("没有完成评教") >= 0) {
				return new NetBugResult("0", "没有完成评教的同学，需要完成评教工作后才能查询成绩");
			}
			
			return new NetBugResult("1", doc);
			
		} catch (IOException e) {
			return NetBugResult.networkError();
		} catch (NullPointerException e) {
			return NetBugResult.networkError();
		}
	}
	
	@Override
	public boolean validateAccount(String stuID ,String password){
		return login(stuID, password, null).getStatus().equals("1");
	}
	
	@Override
	public void logOut(){
        try {
			//getConnection().url("http://jiaowu.zhbit.com/logout.aspx").cookies(getCookies() ).execute();
			//getConnection().url("http://jiaowu.zhbit.com/default2.aspx").cookies(getCookies() ).execute();
        	cookies = null;
        	connection = null;
		} catch (Exception e) {
		}
    }
}
